<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AB对战</title>
    <style>
      h1 {
        width: 500px;
        text-align: center;
      }
      .tips {
        background-color: azure;
        padding: 12px;
        width: 480px;
        text-align: center;
      }
      /*.war-area {
      position: relative;
      background-color: rgb(243, 233, 220);
      border: 2px solid #d8d8d8;
      width: 500px;
      height: 500px;
    }
    .war {
      position: absolute;
      top: calc(50% - 30px);
      left: calc(50% - 30px);
      width: 60px;
      height: 60px;
      background-color: rgb(247, 75, 12);
      display: inline-flex;
      align-items: center;
      justify-content: center;
    }*/

      .war-area {
        position: relative;
        width: 500px;
        height: 360px;
        background-color: antiquewhite;
        margin: 20px auto;
      }
      #war1 {
        position: absolute;
        top: calc(50% - 25px);
        left: calc(50% - 25px);
        width: 50px;
        height: 50px;
        background-color: blueviolet;
      }
    </style>
  </head>
  <body>
    <h1>AB对战</h1>
    <div class="tips">
      两套方向键控制AB对战，攻击武器（剪刀石头布），输的血条掉。
    </div>
    <div class="war-area">
      <div id="war1">
        <div id="a1" style="display: block">剪刀</div>
        <div id="a2" style="display: none">石头</div>
        <div id="a3" style="display: none">布</div>
      </div>
    </div>
    <script>
      function qiehuan() {
        var visible = null;
        for (var i = 1; i <= 3; i++) {
          if (document.getElementById("a" + i).style.display === "block") {
            visible = i;
            break;
          }
        }
        var next = (visible % 3) + 1;
        for (var j = 1; j <= 3; j++) {
          document.getElementById("a" + j).style.display =
            j === next ? "block" : "none";
        }
      }

      var controllerDom = document.getElementById("war1");
      var cleft = parseInt(getComputedStyle(controllerDom).left);
      var ctop = parseInt(getComputedStyle(controllerDom).top);

      document.addEventListener("keydown", (e) => {
        if (e.key === "ArrowLeft") {
          cleft -= 10;
        } else if (e.key === "ArrowRight") {
          cleft += 10;
        } else if (e.key === "ArrowUp") {
          ctop -= 10;
        } else if (e.key === "ArrowDown") {
          ctop += 10;
        } else if (e.key === " ") {
          // 使用 e.key 而不是 event.keyCode
          qiehuan();
        }

        // 限制移动范围
        if (cleft < 0) cleft = 0;
        if (cleft > 450) cleft = 450;
        if (ctop < 0) ctop = 0;
        if (ctop > 310) ctop = 310;

        controllerDom.style.left = cleft + "px";
        controllerDom.style.top = ctop + "px";
      });
    </script>
  </body>
</html>
